package tutor.mina.server;

import java.net.InetSocketAddress;
import java.util.Date;

import javax.net.ssl.SSLContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.KeyStoreFactory;
import org.apache.mina.filter.ssl.SslContextFactory;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class SSLTimeServer {

    static Log log = LogFactory.getLog( SSLTimeServer.class );

    public static void main( final String[] args ) {
        final IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.setHandler( new IoHandlerAdapter() {

            @Override
            public void messageSent( final IoSession session,
                    final Object message )
                throws Exception {
                session.close();
            }

            @Override
            public void sessionOpened( final IoSession session )
                throws Exception {
                session.write( new Date() );
            }

        } );

        try {
            acceptor.getFilterChain().addLast( "ssl",
                    new SslFilter( newSSLContext() ) );
            acceptor.getFilterChain().addLast( "codec",
                    new ProtocolCodecFilter( new TextLineCodecFactory() ) );
            acceptor.getFilterChain().addLast( "logging", new LoggingFilter() );

            acceptor.bind( new InetSocketAddress( 8151 ) );
        }
        catch( final Exception e ) {
            SSLTimeServer.log.info( "Error:", e );
        }
    }

    private static SSLContext newSSLContext()
        throws Exception {
        final KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
        keyStoreFactory
                .setDataUrl( ClassLoader.getSystemResource( "keystore" ) );
        keyStoreFactory.setPassword( "123456" );

        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setProtocol( "TLS" );
        sslContextFactory.setKeyManagerFactoryAlgorithm( "SunX509" );
        sslContextFactory.setKeyManagerFactoryKeyStore( keyStoreFactory
                .newInstance() );
        sslContextFactory.setKeyManagerFactoryKeyStorePassword( "123456" );

        return sslContextFactory.newInstance();
    }

}
